package com.edu.whty.controller;

import com.edu.whty.common.constants.Constant;
import com.edu.whty.common.tools.*;
import com.edu.whty.common.tools.redis.RedisUtil;
import com.edu.whty.entity.base.AttachFile;
import com.edu.whty.entity.disk.*;
import com.edu.whty.entity.school.ProdOwner;
import com.edu.whty.service.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * TODO
 *
 * @author luyao
 * @explain
 * @date 2021/4/29
 */
@Controller
@Component
public class DiskController {

    @Autowired
    private DiskService diskService;

    @Autowired
    private SchoolResourceService schoolResourceService;

    @Autowired
    private FormatService formatService;

    @Autowired
    private ClassificationService classificationService;

    @Autowired
    private AttachFileService attachFileService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    private Logger LOGGER = LogManager.getLogger(DiskController.class);

    private static final String INVALID_FILE = "invalidFile";





    @Value("${rrtbk.opengateDomain}")
    private String opengateDomain;

    @Value("${rrtbk.isCloud}")
    private boolean isCloud;

    @Value("${rrtbk.streamUrl}")
    private String streamUrl;





    /**
    * 创建网盘资源(离线版)
    *
    * @author luyao
    * @date 2021/4/29
    */
   @RequestMapping(value = "/createDiskResource", method = RequestMethod.POST)
   @ResponseBody
   public ResponseMessage createDiskResource(@RequestBody DiskCapacity obj) throws Exception {
       ResponseMessage responseMessage = ResponseMessage.getSuccessResponse();
       String resForm = obj.getResForm();
       String title = obj.getTitle();
       String fid = obj.getFid();
       String url = obj.getUrl();
       obj.setDiskType(0);

       String resId = "";
       if (StringUtils.isBlank(title) || StringUtils.isBlank(fid)) {
           responseMessage.setResult("100000");
           responseMessage.setResultDesc("title不能为空且fid不能为空");
           return responseMessage;
       }
       Map<String, Object> data = MapUtils.newHashMap();
       resId = diskService.createDiskOwnerResource(BeanUtils.beanToMap(obj));
       data.put("contentId", resId);
       responseMessage.setData(data);
       return responseMessage;
   }


    /**
     * （网盘资源-我的收藏）搜索列表
     *
     * @param obj
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryDiskResource", method = RequestMethod.POST)
    @ResponseBody
    public ResponseMessage queryDiskResource(@RequestBody JSONObject obj)  {
        ResponseMessage responseMessage = ResponseMessage.getSuccessResponse();
        DiskOwner diskOwner = new DiskOwner();
        JSONObject pageObj = obj.getJSONObject("page");
        JSONObject queryObj = obj.getJSONObject("query");
        Integer curPage = pageObj.getInt("curPage");
        Integer numPerPage = pageObj.getInt("numPerPage");
        PageHelper.startPage(curPage, numPerPage);
        if (queryObj != null) {
            String parentId=queryObj.optString("parentId");
            if (StringUtils.isNotEmpty(parentId)) {
                diskOwner.setParentId(parentId);
            }else {
                diskOwner.setParentId("0");
            }

            String isFolder=queryObj.optString("isFolder");
            if (StringUtils.isNotEmpty(isFolder)) {
                diskOwner.setIsFolder(isFolder);

            }

            String title = queryObj.optString("title");
            if (StringUtils.isNotEmpty(title)) {
                diskOwner.setTitle(title);
            }

            String format = queryObj.optString("format");
            if (StringUtils.isNotEmpty(format)) {
                diskOwner.setFormatId(format);
            }
            String userId = queryObj.optString("userId");
            if (StringUtils.isNotEmpty(userId)) {
                diskOwner.setUserId(userId);
            }
        }
        List<DiskOwner> diskOwnerList = null;
        try {
            diskOwnerList = diskService.queryDiskOwner(diskOwner);
        } catch (Exception e) {
            LOGGER.info(e);
            responseMessage = ResponseMessage.getFailedResponse();
            responseMessage.setResultDesc("网盘查询失败");
            return responseMessage;
        }
        PageInfo<DiskOwner> pageInfo = new PageInfo<>(diskOwnerList);
        Map<String, Object> data = MapUtils.newHashMap();
        for(DiskOwner diskOwner1:diskOwnerList){
            diskOwner1.setContentId(diskOwner1.getDirId());
            if("0".equals(diskOwner1.getUploadCos())&& "1".equals(diskOwner1.getIsFolder())&&StringUtil.isNotEmpty(diskOwner1.getFid())){
                AttachFile attachFile = attachFileService.getAttachFile(Long.valueOf(diskOwner1.getFid()));
                if (attachFile != null && org.apache.commons.lang.StringUtils.isNotEmpty(attachFile.getFilePathRemote())) {
                    String downloadUrl = "";
                    if (attachFile.getFilePathRemote().contains("data1")) {
                        downloadUrl = streamUrl + attachFile.getFilePathRemote().replace("/gfs_mnt", "");
                    } else {
                        downloadUrl = streamUrl + "/data1" + attachFile.getFilePathRemote();
                    }
                    diskOwner1.setDownloadUrl(downloadUrl);
                    if ("mp4".equals(attachFile.getFileExt().toLowerCase()) || Constant.picList.contains(diskOwner1.getFileExt().toLowerCase())) {
                        diskOwner1.setPreviewUrl(diskOwner1.getDownloadUrl());
                    }
                }
            }
        }
        data.put("list", diskOwnerList);
        data.put("totalCount", Long.valueOf(pageInfo.getTotal()).intValue()); // 总数
        responseMessage.setData(data);
        return responseMessage;

    }

    /**
     * （网盘资源-我的收藏）搜索列表
     *
     * @param SearchObj
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryUserNetdiskDirTree", method = RequestMethod.POST)
    @ResponseBody
    public ResponseMessage querySUserDirTree(@RequestBody JSONObject SearchObj)  {
        List<Map<String , Object>> dirList = new ArrayList<Map<String , Object>>();
        String userId = SearchObj.optString("userId");
        if (org.apache.commons.lang.StringUtils.isEmpty(userId)) {
            ResponseMessage responseMessage = ResponseMessage.getFailedResponse();
            responseMessage.setResult("224001");
            responseMessage.setResultDesc("参数userId不能为空");
            return responseMessage;

        }
        DiskOwner diskOwner0 = new DiskOwner();
        diskOwner0.setUserId(userId);
        diskOwner0.setIsFolder("0");
        List<DiskOwner> list = null;
        try {
            list = diskService.queryDiskOwner(diskOwner0);
        } catch (Exception e) {
            LOGGER.info(e);
            ResponseMessage responseMessage = ResponseMessage.getFailedResponse();
            responseMessage.setResult("224001");
            responseMessage.setResultDesc("网盘树查询失败");
            return responseMessage;
        }
        Map<String , Object> objRoot = new HashMap<String , Object>();
        objRoot.put("id", "0");
        objRoot.put("pId", "-1");
        objRoot.put("name", "根目录");
        dirList.add(objRoot);
        Map<String , Object> obj = null;
        for (DiskOwner diskOwner : list) {
            obj = new HashMap<String , Object>();
            obj.put("id", diskOwner.getDirId());
            obj.put("pId", diskOwner.getParentId());
            obj.put("name", diskOwner.getDirName());

            dirList.add(obj);
        }
        Map<String, Object> data = MapUtils.newHashMap();
        data.put("dirList", dirList);
        ResponseMessage responseMessage = ResponseMessage.getSuccessResponse();
        responseMessage.setData(data);
        return responseMessage;
    }



    /**
     * @Author  xiongxiaofei
     * @Date  2017/3/21
     * @Desc  删除网盘资源
     */
    @RequestMapping(value = "/removeResource", method = RequestMethod.POST)
    @ResponseBody
    public ResponseMessage removeResource(@RequestBody DiskOwner netdiskDTO) {
        ResponseMessage responseMessage = ResponseMessage.getSuccessResponse();
        try {
            diskService.removeResource(netdiskDTO);
        } catch(Exception ex) {
            LOGGER.error(ex.getMessage(),ex);
            responseMessage = ResponseMessage.getFailedResponse();
            responseMessage.setResultDesc("删除资源失败");
        }
        return responseMessage;
    }


    /**
     * 获取资源详情接重命名口
     *
     * @param resId
     * @return
     * @throws Exception
     * @author xiongxf
     * @date 2014年9月5日
     */
    @RequestMapping(value = "/resourceDetail/{resId}", method = RequestMethod.GET)
    @ResponseBody
    public ResponseMessage resourceDetail(@PathVariable String resId) throws Exception {

        ResponseMessage responseMessage = ResponseMessage.getSuccessResponse();

        if (org.apache.commons.lang.StringUtils.isBlank(resId)) {
             responseMessage = ResponseMessage.getFailedResponse();
            responseMessage.setResultDesc("参数resId不能为空");
            return responseMessage;
        }
        DiskOwner diskOwner = diskService.getDiskOwner(resId);

        if (diskOwner == null) {
            ProdOwner prodOwner =  schoolResourceService.getProdOwnerByResId(resId);
            if(prodOwner == null) {
                responseMessage = ResponseMessage.getFailedResponse();
                responseMessage.setResultDesc("资源不存在");
                return responseMessage;
            }
            prodOwner.setViewCount(prodOwner.getViewCount()+1);
            schoolResourceService.updateViewCount(prodOwner);
            getDownloadPlayUrl(prodOwner);
            responseMessage.setData(prodOwner);
            return responseMessage;
        }
        diskOwner.setViewCount(diskOwner.getViewCount()+1);
        diskService.updateDiskOwner(diskOwner);
        getDownloadPlayUrl(diskOwner);
        responseMessage.setData(diskOwner);
        return responseMessage;
    }


    /**
     * 查询资源格式
     *
     * @param
     * @return
     * @throws Exception
     * @author chenmeng
     * @date 2015年2月28日
     */
    @RequestMapping(value = "/getFormatList", method = RequestMethod.GET)
    @ResponseBody
    public ResponseMessage getFormatList() throws Exception {
        LOGGER.debug("查询资源格式...");
        Map<String, Object> data = MapUtils.newHashMap();
        @SuppressWarnings("unchecked")
        List<FormatDTO> result=(List<FormatDTO>)redisUtil.get("getFormatList");
        if(result==null){
            FormatDTO formatDTO = new FormatDTO();
            List<FormatDTO> formatDTOlist = formatService.queryFormatList(formatDTO);
            data.put("resTypeList", formatDTOlist);
            redisUtil.set("getFormatList", result, 24 * 60 * 60);
        }else{
            data.put("resTypeList", result);
        }

        ResponseMessage responseMessage = ResponseMessage.getSuccessResponse();
        responseMessage.setData(data);
        return responseMessage;
    }

    /**
     * 查询资源格式
     * @author	chenmeng
     * @date	2015年2月28日
     * @param
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/queryClassificationList", method=RequestMethod.GET)
    @ResponseBody
    public ResponseMessage queryClassificationList()
            throws Exception {

        ClassificationDTO classification = new ClassificationDTO();
        classification.setStatus("0");
        List<ClassificationDTO> classificationList = classificationService.findClassificationList(classification);

        Map<String, Object> data = MapUtils.newHashMap();
        data.put("classificationList", classificationList);

        ResponseMessage responseMessage = ResponseMessage.getSuccessResponse();
        responseMessage.setData(data);
        return responseMessage;
    }



    /**
     * 获取文件播放地址、流媒体地址、缩略图地址、下载地址
     *
     * @param jsonObj
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getPlayPrevAndThumbUrl", method = RequestMethod.POST)
    @ResponseBody
    public ResponseMessage getPlayPrevAndThumbUrl(@RequestBody JSONObject jsonObj, HttpServletRequest request) throws Exception {
        LOGGER.info("请求参数："+jsonObj);
        long start = System.currentTimeMillis();
        ResponseMessage rm = ResponseMessage.getSuccessResponse();
        /** 下载类型（1：根据fid获取，2：根据resId获取，3：根据产品code获取） **/
        String type = jsonObj.optString("type");
        String bcePicSpec = jsonObj.optString("bcePicSpec");
        if (org.apache.commons.lang.StringUtils.isBlank(type)) {
            rm = ResponseMessage.getFailedResponse();
            rm.setResultDesc("参数type为空！");
            return rm;
        }
        rm = getPlayPrevAndThumbUrlHJY(type,jsonObj,bcePicSpec, request);
        long end = System.currentTimeMillis();
        LOGGER.info("返回的数据："+rm.getData().toString());
        LOGGER.info("方法getPlayPrevAndThumbUrl的执行时间："+(end-start)+"ms");
        return rm;
    }


    /**
     * 慧教云获取文件播放地址、流媒体地址和缩略图地址
     * @return
     * @param type
     * @param jsonObj
     * @param bcePicSpec
     */
    private ResponseMessage getPlayPrevAndThumbUrlHJY(String type, JSONObject jsonObj, String bcePicSpec, HttpServletRequest request) throws Exception {
        ResponseMessage rm = ResponseMessage.getSuccessResponse();
        JSONArray jsonArr = new JSONArray();
        if ("1".equals(type)) {
            JSONArray fidArr = jsonObj.optJSONArray("fidArr");
            if (fidArr==null || fidArr.contains("{}")) {
                rm = ResponseMessage.getFailedResponse();
                rm.setResultDesc("参数fidArr为空！ 请检查输入参数");
                return rm;
            }
            for (int i = 0; i < fidArr.size(); i++) {
                JSONObject obj = new JSONObject();
                obj.put("fid", Long.valueOf(fidArr.getString(i)));
//                getPlayPrevAndThumbUrlByFid(Long.valueOf(fidArr.getString(i)), obj, bcePicSpec, request);
//                if ("1".equals(obj.optString(INVALID_FILE))) {
//                    obj.put(INVALID_FILE, true);
//                    obj.put("desc", "无效数据");
//                } else {
//                    obj.put("playUrl", new StringBuilder(cmsportalUrl).append("/viewHtml5ByFid.html?fid=").append(fidArr.getString(i)).toString());
//                    String downUrl = getDownUrlByFid(Long.valueOf(fidArr.getString(i)));
//                    obj.put("downUrl", downUrl);
//                }
//                jsonArr.add(obj);
            }
        } else if ("2".equals(type)) {
            JSONArray resIdArr = jsonObj.optJSONArray("resIdArr");
            LOGGER.info("resIdArr------>:" + resIdArr.size());
            if (resIdArr==null || resIdArr.contains("{}")) {
                rm = ResponseMessage.getFailedResponse();
                rm.setResultDesc("参数resIdArr为空！ 请检查输入参数");
                return rm;
            }
            for (int i = 0; i < resIdArr.size(); i++) {
                DiskOwner diskOwner= diskService.getDiskOwner(resIdArr.getString(i));
                JSONObject obj = new JSONObject();
                obj.put("resId", resIdArr.getString(i));
                if (diskOwner != null) {
                    getDownloadPlayUrl(diskOwner);
                    obj.put("playUrl",diskOwner.getPlayUrl());
                    obj.put("downUrl",diskOwner.getDownloadUrl());
                } else {
                    obj.put(INVALID_FILE, true);
                    obj.put("desc", "无效数据");
                }
                jsonArr.add(obj);
            }
        } else if ("3".equals(type)) {
            JSONArray productCodeArr = jsonObj.optJSONArray("productCodeArr");
            if (productCodeArr==null || productCodeArr.contains("{}")) {
                rm = ResponseMessage.getFailedResponse();
                rm.setResultDesc("参数productCodeArr为空！ 请检查输入参数");
                return rm;
            }
            for (int i = 0; i < productCodeArr.size(); i++) {
                String productCode = productCodeArr.getString(i);
                JSONObject obj = new JSONObject();
                obj.put("productCode", productCode);
//                List<Map<String, Object>> mapList = schoolResourceService.getFolderByDirID(productCode);
//                if (mapList != null && !mapList.isEmpty()) {
//                    if (mapList.size() > 1) {//资源包
//                        obj.put("existPrev", false);
//                        obj.put("existThum", false);
//                    } else {//单个资源产品
//                        com.whty.cms.api.resource.entity.Resource resource = resourceService.getSimpleResource(
//                                (String) mapList.get(0).get("RESID"));
//                        getPlayPrevAndThumbUrlByFid(Long.valueOf(resource.getFid()), obj, bcePicSpec, request);
//                        if ("1".equals(obj.optString(INVALID_FILE))) {
//                            obj.put(INVALID_FILE, true);
//                            obj.put("desc", "无效数据");
//                        } else {
//                            obj.put("playUrl", new StringBuilder(cmsportalUrl).append("cms-portal/viewHtml5ByFid.html?fid=").append(resource.getFid()).toString());
//                        }
//                    }
//                    String downUrl = new StringBuilder().append(SysConf.getString("webapp.cmsftUrl"))
//                            .append("/downloadPro?productCode=").append(productCode).toString();
//                    obj.put("downUrl", downUrl);
//                } else {
//                    obj.put(INVALID_FILE, true);
//                    obj.put("desc", "无效数据");
//                }
//                jsonArr.add(obj);
            }
        } else {
            rm = ResponseMessage.getFailedResponse();
            rm.setResultDesc("参数type传值错误！");
            return rm;
        }
        JSONObject data = new JSONObject();
        data.put("playPrevAndThumb", jsonArr);
        rm.setData(data);
        return rm;
    }


    private void getDownloadPlayUrl(DiskOwner diskOwner) throws Exception{
        if("0".equals(diskOwner.getUploadCos())&&StringUtil.isNotEmpty(diskOwner.getFid())) {
            AttachFile attachFile = attachFileService.getAttachFile(Long.valueOf(diskOwner.getFid()));
            if(attachFile != null&& org.apache.commons.lang.StringUtils.isNotEmpty(attachFile.getFilePathRemote())) {
                String downloadUrl = "";
                if(attachFile.getFilePathRemote().contains("data1")) {
                    downloadUrl =  streamUrl+attachFile.getFilePathRemote().replace("/gfs_mnt", "");
                }else {
                    downloadUrl = streamUrl+"/data1"+attachFile.getFilePathRemote();
                }
                diskOwner.setDownloadUrl(downloadUrl);
                if (Constant.picList.contains(attachFile.getFileExt().toLowerCase()) || Constant.videoList.contains((attachFile.getFileExt().toLowerCase()))) {
                    diskOwner.setPreviewUrl(diskOwner.getDownloadUrl());
                }
            }
        }
    }

    @RequestMapping(value = "/createFolder", method = RequestMethod.POST)
    @ResponseBody
    public ResponseMessage createFolder(@RequestBody FolderDTO folderDTO) {
        ResponseMessage responseMessage = ResponseMessage.getSuccessResponse();
        try {
            /** 如果是第三方应用调用的接口，则将文件夹放在默认文件夹"应用资源"下 */

            String dirId = diskService.createFolder(folderDTO);
            Map<String, String> data = MapUtils.newHashMap();
            data.put("dirId", dirId);
            responseMessage.setData(data);
        } catch(Exception ex) {
            ex.printStackTrace();
            responseMessage = ResponseMessage.getFailedResponse();
            responseMessage.setResultDesc(ex.getMessage());
        }
        return responseMessage;
    }


    //	网盘容量查询
    @RequestMapping(value = "/getCapacity/{diskType}/{uid}", method=RequestMethod.GET)
    @ResponseBody
    public JSONObject getCapacity(@PathVariable String diskType, @PathVariable String uid) {
        JSONObject jsonObj = new JSONObject();
        if (redisUtil.hasKey("disk_" + uid)) {
          String  jsonObjStr =  redisUtil.get("disk_" + uid).toString();
            jsonObj = JSONObject.fromObject(jsonObjStr);
            return jsonObj;
        }

        String url = null;
        try {
            url = opengateDomain + "/cms-gateway/getCapacity/" + diskType + "/" + uid + "?accessToken=" + OpenUtil.createToken();
        } catch (Exception e) {
            LOGGER.error("获取信息异常");
        }
        String aamResponse = HttpClient.doGetMethod(url);
        jsonObj = JSONObject.fromObject(aamResponse);
        redisUtil.set("disk_" + uid,aamResponse,1800);
        return jsonObj;
    }

    /**
     * @param folderDTO
     * @return
     * @throws Exception
     * @author xiongxiaofei
     * @date 2015年1月28日
     * @desc 重命名文件夹
     */
    @RequestMapping(value = "/renameFolder", method = RequestMethod.POST)
    @ResponseBody
    public ResponseMessage renameFolder(@RequestBody FolderDTO folderDTO) {
        ResponseMessage responseMessage = ResponseMessage.getSuccessResponse();
        try {
            String dirId = folderDTO.getDirId();
            String dirName = folderDTO.getDirName();
            if (StringUtils.isEmpty(dirId) || StringUtils.isEmpty(dirName)) {
                responseMessage = ResponseMessage.getFailedResponse();
                responseMessage.setResult("224001");
                responseMessage.setResultDesc("参数dirId或dirName不能为空");
                return responseMessage;
            }
            //验证文件夹名是否重名
            String sql = "select count(1) from t_disk_owner where dir_name=? and user_id=(select user_id from t_disk_owner where dir_id=?)";
            int count =jdbcTemplate.queryForObject(sql, new Object[]{dirName.trim(),dirId}, Integer.class);
            if (count>0) {
                responseMessage = ResponseMessage.getFailedResponse();
                responseMessage.setResult("224002");
                responseMessage.setResultDesc("文件名称已存在");
                return responseMessage;
            }

            diskService.renameFolder(folderDTO);
        } catch(Exception ex) {
            ex.printStackTrace();
            responseMessage = ResponseMessage.getFailedResponse();
            responseMessage.setResultDesc(ex.getMessage());
        }
        return responseMessage;
    }


    //2.1.19	移动文件接口
    @RequestMapping(value="/moveFiles",method=RequestMethod.POST)
    @ResponseBody
    public ResponseMessage moveFiles(@RequestBody JSONObject obj) throws Exception{
//        Integer diskType = (Integer)obj.optInt("diskType");
//        String uid = obj.optString("uid");
        String parentCatalogId = obj.optString("parentCatalogId"); //移动的位置
        JSONArray contentIds = obj.optJSONArray("contentIds");  //数组资源或目录
//        Map<String,Object> map =  MapUtils.newHashMap();
        //去掉修改用户id和群组id的逻辑，理论上文件的移动应该是内部的移动，不存在修改文件所属者的id
		/*map.put("ownerType", diskType.toString());
		if(diskType == 0){
			map.put("userId", uid);
		}
		if(diskType == 1){
			map.put("groupId", uid);
		}*/
//        map.put("parentId", parentCatalogId);
//        map.put("modifyTime", new Date());
        DiskOwner diskOwner = new DiskOwner();
        diskOwner.setParentId(parentCatalogId);
        diskOwner.setModifyTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        if(StringUtils.isNotBlank(parentCatalogId)){
            for (Object contentId : contentIds) {
//                map.remove("dirId");
//                map.put("dirId", contentId.toString());
                diskOwner.setDirId(contentId.toString());
                diskService.updateDiskOwner(diskOwner);
            }
        }
        ResponseMessage responseMessage = ResponseMessage.getSuccessResponse();
        return responseMessage;
    }

    /**
     * 增加资源/产品下载次数
     *
     * @param strBody
     * @return
     * @throws Exception
     * @author xiongxf
     * @date 2014年9月5日
     */
    @RequestMapping(value = "/addDownCount", method = RequestMethod.POST)
    @ResponseBody
    public ResponseMessage addDownCount(@RequestBody String strBody) throws Exception {
        ResponseMessage responseMessage = ResponseMessage.getSuccessResponse();
        LOGGER.debug("增加资源/产品下载次数...");
        JSONObject jsonBody = JSONObject.fromObject(strBody);
        String downType = jsonBody.optString("downType");
        String downId = jsonBody.optString("downId");
        if (org.apache.commons.lang.StringUtils.isEmpty(downType) || org.apache.commons.lang.StringUtils.isEmpty(downId)) {
             responseMessage = ResponseMessage.getFailedResponse();
            responseMessage.setResultDesc("downType或downId不能为空");
            return responseMessage;
        }

        if (!Constant.DOWN_TYPE_RES.equals(downType) && !Constant.DOWN_TYPE_PROD.equals(downType)) {
             responseMessage = ResponseMessage.getFailedResponse();
            responseMessage.setResultDesc("downType参数值不正确");
            return responseMessage;
        }

        //学校门户本校资源下载调用时没有添加日志记录，2019年7月30号加上
        boolean flag = false;//是否传了userId，传了就加下载记录日志
        try {
            /** 资源下载 */
            if (Constant.DOWN_TYPE_RES.equals(downType)) {
                DiskOwner resource = diskService.getDiskOwner(downId);
                if(resource !=null){
                    resource.setDownCount(resource.getDownCount()+1);
                diskService.updateDiskOwner(resource);
                } else {
                     responseMessage = ResponseMessage.getFailedResponse();
                    responseMessage.setResultDesc("查询不到该资源");
                    return responseMessage;
                }
            }


        /** 产品下载 */
        if (Constant.DOWN_TYPE_PROD.equals(downType)) {
            ProdOwner product = schoolResourceService.getProdOwner(downId);
            if (product != null) {
                product.setDownCount(product.getDownCount() + 1);
                schoolResourceService.updateDownCount(product);
            } else {
                 responseMessage = ResponseMessage.getFailedResponse();
                responseMessage.setResultDesc("查询不到该产品");
                return responseMessage;
            }
        }

        return ResponseMessage.getSuccessResponse();
        } catch(Exception ex ) {
            ex.printStackTrace();
             responseMessage = ResponseMessage.getFailedResponse();
            responseMessage.setResultDesc(ex.getMessage());
            return responseMessage;
        }
    }

    private void getDownloadPlayUrl(ProdOwner prodOwner) throws Exception{
        prodOwner.setPlayUrl("");
        if(org.apache.commons.lang3.StringUtils.isNotEmpty(prodOwner.getDownloadUrl())&&isCloud) {
            if("mp4".equals(prodOwner.getFileExt().toLowerCase())||"FMT02".equals(prodOwner.getFormatId())) {
                prodOwner.setPlayUrl(prodOwner.getDownloadUrl());
            }
        }else {
            AttachFile attachFile = attachFileService.getAttachFile(Long.valueOf(prodOwner.getFId()));
            if(attachFile != null&& org.apache.commons.lang.StringUtils.isNotEmpty(attachFile.getFilePathRemote())) {
                String downloadUrl = "";
                if(attachFile.getFilePathRemote().contains("data1")&& org.apache.commons.lang.StringUtils.isNotEmpty(attachFile.getFilePathRemote())) {
                    downloadUrl = streamUrl+attachFile.getFilePathRemote().replace("/gfs_mnt", "");
                }else {
                    downloadUrl = streamUrl+"/data1"+attachFile.getFilePathRemote();
                }
                prodOwner.setDownloadUrl(downloadUrl);
                if (Constant.picList.contains(attachFile.getFileExt().toLowerCase()) || Constant.videoList.contains((attachFile.getFileExt().toLowerCase()))) {
                    prodOwner.setPreviewUrl(prodOwner.getDownloadUrl());
                }
            }
        }
    }


    /**
     * @param
     * @return
     * @throws Exception
     * @author xiongxiaofei
     * @date 2015年1月28日
     * @desc 修改网盘资源
     */
    @RequestMapping(value = "/updateDiskRes", method = RequestMethod.POST)
    @ResponseBody
    public ResponseMessage updateDiskRes(@RequestBody DiskOwner diskOwner) {
        ResponseMessage responseMessage = ResponseMessage.getSuccessResponse();
        try {
            diskService.updateDiskOwner(diskOwner);
        } catch(Exception ex) {
            ex.printStackTrace();
            responseMessage = ResponseMessage.getFailedResponse();
            responseMessage.setResultDesc(ex.getMessage());
        }
        return responseMessage;
    }

}
